var express = require('express');
var app = express();
const RedisClient = require('./redis_client');
const task_api = require("./server/class/task");
require('./server/class/schedule');
const PORT = process.env.PORT || 15000;

// 启动服务器
async function startServer() {
    try {
        // 初始化Redis连接（只调用一次）
        console.log('🔄 Initializing Redis connection...');
        await RedisClient.init();

        // 启动Express服务器
        app.listen(PORT, () => {
            console.log(`🚀 Server running on port ${PORT}`);
            console.log(`🔗 Health check: http://localhost:${PORT}/health`);
        });
    } catch (error) {
        console.error('❌ Failed to start server:', error);
        process.exit(1);
    }
}

app.get('/api/data/:key', (req, res) => {
    const {key} = req.params;
    task_api.get_blood_war_info_one(key, function (result) {
        if (result==0){
            res.send('{"code":500,"msg":"查询错误"}');
        }else if (result==1){
            res.send('{"code":200,"msg":"success","data":[]}');
        }else
            res.json({key, data: result || 'Not found'});
    });
});

app.get('/api/robot', (req, res) => {
    const {key} = req.params;
    task_api.get_robot_info( function (result) {
        if (result==0){
            res.send('{"code":500,"msg":"查询错误"}');
        }else if (result==1){
            res.send('{"code":200,"msg":"success","data":[]}');
        }else
            res.json({key, data: result || 'Not found'});
    });
});

//获取铁血战争统计
app.get('/api/getBloodWarInfoByType', function (req, res){
    if (!req.query.type || !req.query.flag){
        return res.status(400).json({error: '请求参数不能为空'});
    }
    task_api.get_blood_war_info(req, function (result) {
        // console.log("结果返回======:",result);
        if (result==0){
            res.send('{"code":500,"msg":"查询错误"}');
        }else if (result==1){
            res.send('{"code":200,"msg":"success","data":[]}');
        }else{
            res.writeHead(200, {"Content-Type": "text/plain;charset=utf-8"});
            res.write('{"code":200,"msg":"success","data":'+JSON.stringify(result)+'}');
            res.end();
        }
    });
});

app.get('/api/getUserToBackList/:key', function (req, res){
    const {key} = req.params;
    task_api.get_user_black_list(key,function (result) {
        if (result==0){
            res.send('{"code":500,"msg":"查询错误"}');
        }else if (result==1){
            res.send('{"code":200,"msg":"success","data":[]}');
        }else
            res.json({key, data: result || 'Not found'});
    })
});

app.get('/api/getRobotFlag',function  (req, res)  {
    const {key} = req.params;
    task_api.get_robot_flag( function (result) {
        if (result==0){
            res.send('{"code":500,"msg":"查询错误"}');
        }else if (result==1){
            res.send('{"code":200,"msg":"success","data":[]}');
        }else
            res.json({key, data: result || 'Not found'});
    });
});


app.get('/api/getOnceInfo',function (req, res) {
    if(!req.query.userId || !req.query.prop_id){
        return res.status(400).json({error: '请求参数不能为空'});
    }
    var propId = req.query.prop_id;
    var userId = req.query.userId;
    console.log(userId);
    task_api.get_user_once( propId,function (result) {
        if (result==0){
            res.send('{"code":500,"msg":"查询错误"}');
        }else if (result==1){
            res.send('{"code":200,"msg":"success","data":[]}');
        }else
            res.json({key, data: result || 'Not found'});
    });
});


//Test
app.get('/api/getUserTest', function (req, res) {
    task_api.get_user_test(req,(result) => {
        if (result==0){
            res.send('{"status":1,"msg":"查询错误"}');
        }else{
            res.writeHead(200, {"Content-Type": "text/plain"});
            res.write('{"code":200,"msg":"success","data":['+JSON.stringify(result)+']}');
            res.end();
        }

    });
});


// 启动应用
startServer();
